import os
import subprocess
import time
from utility.sql_helper import MysqlHelper


class Codes(object):
    def __init__(self, code=''):
        self._sql = MysqlHelper()
        self.code = code
        # self.timeout = 60000
        # self.run_time = 0
        # 根据开始时间创建临时文件
        self.start_time = time.strftime("%Y%m%d_%H%M%S", time.localtime(time.time()))
        self.filename = self.start_time + '.py'
        # 工作目录
        self.root = os.getcwd()
        # 临时文件夹目录
        self.path = self.root + '\\Temp'

    # 添加历史记录
    def insert_code(self, result, user_id):
        sql = 'INSERT INTO codes (code_context, code_result, user_id) VALUES(%s, %s, %s);'
        params = (self.code, result, user_id)
        return self._sql.insert(sql, params)

    # 获取历史记录
    def get_codes(self, user_id):
        sql = 'SELECT * FROM codes WHERE user_id=%s;'
        params = user_id
        list_data = self._sql.get_all(sql, params)
        return list_data

    # 清空历史记录
    def clear_codes(self, user_id):
        sql = 'DELETE FROM codes WHERE user_id=%s;'
        params = user_id
        res = self._sql.delete(sql, params)
        return res

    # 删除历史记录
    def delete_code(self, code_id):
        sql = 'DELETE FROM codes WHERE code_id=%s;'
        params = code_id
        res = self._sql.delete(sql, params)
        return res

    def interpret(self):
        # 创建临时文件和文件夹
        self.build_temp()
        self.build_tempfile()
        p = subprocess.Popen("python " + self.filename, shell=True, close_fds=True, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        out, err = p.communicate()
        # 删除临时文件和文件夹
        self.delete_tempfile()
        self.delete_temp()
        return {"out": out.decode(), "err": err.decode()}

    def get_result(self, problem_id):
        sql = 'SELECT * FROM result WHERE problem_id=%s'
        params = problem_id
        res = self._sql.get_one(sql, params)
        return res

    def update_ac_times(self, problem_id):
        sql = 'UPDATE problems SET AC_times=AC_times+1 WHERE problem_id=%s'
        params = problem_id
        res = self._sql.update(sql, params)
        return res

    def update_all_times(self, problem_id):
        sql = 'UPDATE problems SET all_times=all_times+1 WHERE problem_id=%s'
        params = problem_id
        res = self._sql.update(sql, params)
        return res

    # 创建临时文件夹
    def build_temp(self):
        if not os.path.exists(self.path):
            os.makedirs(self.path)
            print(self.path + ' has been built')
        os.chdir(self.path)

    # 创建临时文件
    def build_tempfile(self):
        if not os.path.exists(self.filename):
            f = open(self.filename, 'w')
            f.write(self.code)
            f.close()
            print(self.filename + ' has been built')

    # 删除临时文件
    def delete_tempfile(self):
        if os.path.exists(self.filename):
            os.remove(self.filename)
            print(self.filename + ' has been deleted')
        else:
            print('no such file:%s' % self.filename)

    # 删除临时文件夹
    def delete_temp(self):
        os.chdir(self.root)
        if os.path.exists(self.path):
            try:
                os.rmdir(self.path)
                print(self.path + ' has been deleted')
            except:
                print(self.path + ' is not empty')
        else:
            print('no such path')
